package org.senseframework.support.orm.mybatis.mysql;

import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.support.SqlSessionDaoSupport;
import org.senseframework.support.core.dto.PageData;
import org.senseframework.support.orm.mybatis.query.builder.InsertBuilder;
import org.senseframework.support.orm.mybatis.query.builder.QueryBuilder;
import org.senseframework.support.orm.mybatis.query.builder.UpdateBuilder;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Author lanjian
 * Email  jianlan@iflytek.com
 */
public abstract class AbstractMySqlBaseDao<T> extends SqlSessionDaoSupport implements MySqlBaseDao<T> {
    @Autowired
    public void setSqlSessionTemplate(SqlSessionTemplate sqlSessionTemplate) {
        super.setSqlSessionTemplate(sqlSessionTemplate);
    }

    protected abstract Class mapperClass();

    public String namespace() {
        if (mapperClass() == null) {
            throw new RuntimeException("not impl");
        }
        return mapperClass().getName();
    }

    public int update(UpdateBuilder updateBuilder) {
        MysqlBaseMapper k = (MysqlBaseMapper) getSqlSession().getMapper(mapperClass());
        return k.update(updateBuilder);
    }

    public int insert(InsertBuilder insertBuilder) {
        MysqlBaseMapper k = (MysqlBaseMapper) getSqlSession().getMapper(mapperClass());
        return k.insert(insertBuilder);
    }

    public int count(QueryBuilder queryBuilder) {
        MysqlBaseMapper k = (MysqlBaseMapper) getSqlSession().getMapper(mapperClass());
        return k.count(queryBuilder);
    }

    public List<T> list(QueryBuilder queryBuilder) {
        MysqlBaseMapper k = (MysqlBaseMapper) getSqlSession().getMapper(mapperClass());
        return k.list(queryBuilder);
    }

    public T one(QueryBuilder queryBuilder) {
        MysqlBaseMapper k = (MysqlBaseMapper) getSqlSession().getMapper(mapperClass());
        return (T) k.one(queryBuilder);
    }

    @Override
    public <K>K sum(QueryBuilder queryBuilder) {
        MysqlBaseMapper k = (MysqlBaseMapper) getSqlSession().getMapper(mapperClass());
        return (K) k.sum(queryBuilder);
    }

    public PageData page(QueryBuilder queryBuilder) {
        PageData pageData = new PageData();
        pageData.setCount(count(queryBuilder));
        pageData.setList(list(queryBuilder));
        pageData.setPageNumber(queryBuilder.getPage());
        pageData.setPageSize(queryBuilder.getSize());
        return pageData;
    }
}
